package test

import (
	"crypto/cipher"
	"crypto/rand"

	"github.com/emmansun/gmsm/sm4"
)

func Sm4CBCPkcs7Encrypt(plaintext, iv, key []byte) ([]byte, error) {
	block, err := sm4.NewCipher(key)
	if err != nil {
		panic(err)
	}

	blockSize := block.BlockSize()
	if plaintext, err = pkcs7Pad(plaintext, blockSize); err != nil {
		return nil, err
	}
	ciphertext := make([]byte, len(plaintext))
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext, plaintext)

	return ciphertext, nil
}

func Sm4CBCPkcs7Decrypt(encryptData, iv, key []byte) ([]byte, error) {
	block, err := sm4.NewCipher(key)
	if err != nil {
		panic(err)
	}

	blockSize := block.BlockSize()

	if iv == nil {
		iv = make([]byte, blockSize)
		if _, err := rand.Read(iv); err != nil {
			return nil, err
		}
	}

	if len(encryptData)%blockSize != 0 {
		panic("ciphertext is not a multiple of the block size")
	}

	mode := cipher.NewCBCDecrypter(block, iv)

	mode.CryptBlocks(encryptData, encryptData)
	if encryptData, err = pkcs7Unpad(encryptData, blockSize); err != nil {
		return nil, err
	}
	return encryptData, nil
}
